package com.qkm.xinguan.controller;


import com.qkm.xinguan.domain.entity.Notice;
import com.qkm.xinguan.domain.entity.Order;
import com.qkm.xinguan.domain.transform.dto.OrderDTO;
import com.qkm.xinguan.exception.BindingResultException;
import com.qkm.xinguan.exception.BusinessException;
import com.qkm.xinguan.repository.OrderRepository;
import com.qkm.xinguan.response.Result;
import com.qkm.xinguan.response.ResultCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author zfj
 * @date 2021/12/22 -11:39
 */
@RestController
public class OrderController implements IOrderController {
	private final OrderRepository orderRepository;

	@Autowired
	public OrderController(OrderRepository orderRepository) {
		this.orderRepository = orderRepository;
	}

	@Override
	public Result addOrder(OrderDTO orderDTO, BindingResult result) {
		if (result.hasErrors()) {
			throw new BindingResultException(result);
		}
		boolean b = orderRepository.save(execute(orderDTO,null));
		if (b) {
			return Result.ok().message("订单添加成功");
		} else {
			throw new BusinessException(ResultCode.ORDER_ACCOUNT_IS_ZERO.getCode(), "添加订单失败");
		}
	}

	@Override
	public Result deleteOrder(Long tourist, Long houseId) {
		boolean b=orderRepository.deleteByHouseId(tourist,houseId);
		if(b){
			return Result.ok().message("删除订单成功");
		}
		throw new BusinessException("订单不存在");
	}

//	@Override
//	public Result deleteOrder(Long id) {
//		Order order=orderRepository.getById(id);
//		if(Objects.isNull(order)){
//			throw new BusinessException(ResultCode.ORDER_ACCOUNT_NOT_EXIST);
//		}
//		boolean b=orderRepository.removeById(id);
//		if(b){
//			return Result.ok().message("删除订单成功");
//		}
//		throw new BusinessException("删除订单失败");
//	}

	@Override
	public Result getAllOrderById(Long id) {
		return orderRepository.getAllOrderById(id);
	}

	@Override
	public Result clearOrder(Long tourist) {
		boolean b= orderRepository.clearOrder(tourist);
		if(b){
			return Result.ok().message("删除订单");
		}
		throw new BusinessException("订单不存在");
	}

	/**
	 * 构建实体类对象
	 *
	 * @param orderDTO 订单传输对象
	 * @return User
	 */
	public static Order execute(OrderDTO orderDTO, Long id) {
		Order order = new Order();
		BeanUtils.copyProperties(orderDTO, order);
		order.setId(id);
		return order;
	}
}
